﻿using System.Collections.Generic;
using Entitas;
using Script.Other;
using UnityEngine;

/// <summary>
/// if Input, what the player has to do
/// </summary>
public class InputProcessSystem : ReactiveSystem<InputEntity>
{
    private readonly Contexts           context;
    private readonly IGroup<GameEntity> group;
    private          Camera             mainCamera;

    public InputProcessSystem (Contexts context) : base (context.input)
    {
        this.context = context;
        group        = context.game.GetGroup (GameMatcher.PlayerTag);
        mainCamera   = Camera.main;
    }

    public InputProcessSystem (ICollector<InputEntity> collector) : base (collector) { }

    protected override ICollector<InputEntity> GetTrigger (IContext<InputEntity> context)
    {
        return context.CreateCollector (InputMatcher.InputComp);
    }

    protected override bool Filter (InputEntity entity)
    {
        return true;
    }

    protected override void Execute (List<InputEntity> entities)
    {
        var playerEntity = group.GetSingleEntity ();

        foreach (var inputEntity in entities)
        {
            playerEntity.ReplaceVelComp (new Vector2 (
                inputEntity.inputComp.Dir.x,
                inputEntity.inputComp.Dir.y
            ));

            var mousePos = inputEntity.inputComp.mousePos;
            var worldPos = mainCamera.ScreenToWorldPoint (mousePos);
            var dir      =new Vector2 (worldPos.x,worldPos.y)-playerEntity.posComp.pos;
            var angle    = dir.Vector2Float ();
            playerEntity.ReplaceRotComp (angle);

            if (inputEntity.inputComp.Fire)
            {
                playerEntity.AddCreateBulletCmdComp (angle);
            }
        }
    }
}